package com.lib76.buildCode;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.lib76.buildCode.dao.ProjectDao;
import com.lib76.buildCode.model.Project;
import com.lib76.buildCode.service.ProjectXmlServer;
import com.lib76.buildCode.service.VelocityServer;

/**
 * 网站启动监听
 * @author 张浩
 * @version 0.0.1(2013-11-2)
 */
public class ContextListener implements ServletContextListener{

	public void contextDestroyed(ServletContextEvent event) {}

	public void contextInitialized(ServletContextEvent event) {
		Properties prop = new Properties();
		try {
            InputStream is = ContextListener.class.getResource("/velocity.properties").openStream();
            prop.load(is);
			prop.setProperty(VelocityServer.RESOURCE_PATH_KEY, event.getServletContext().getRealPath(prop.getProperty(VelocityServer.RESOURCE_PATH_KEY)));
			VelocityServer.initial(prop);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//加载XML
		String path = event.getServletContext().getRealPath("/WEB-INF/project");
		File file = new File(path);
		if(file.exists()){
			file.listFiles(new FileFilter(){
				public boolean accept(File file) {
					if(file.getName().endsWith(".xml")){
						Project project = ProjectXmlServer.parseXml(file);
						ProjectDao.save(project);
					}
					return false;
				}
			});
		}else{file.mkdir();}
	}

}
